﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Shake.Framework.Contents;
using Shake.Business.Infrastructures;
using Shake.Business.Resources;

namespace Shake.Business.Services
{
    public class JavascriptBuildService : IJavascriptBuildService
    {
        private static readonly List<string> _directories = new List<string>
        { 
            "Public/models",
            "Public/modules"
        };

        public void BuildRequireJsConfig()
        {
            var files = new List<FileInfo>();
            //var featureDirs = Directory.GetDirectories(PathConfiguration.PluginDirectoryFullName);
            //foreach (var featureDir in featureDirs)
            //{
            //    var jsFiles = GetJavascriptFileFullNames(featureDir);
            //    files.AddRange(jsFiles);
            //}

            var mainProjectJsFiles = GetJavascriptFileFullNames(AppDomain.CurrentDomain.BaseDirectory);
            files.AddRange(mainProjectJsFiles);

            StringBuilder sb = new StringBuilder();
            files.ForEach(fileInfo =>
            {
                var name = Path.GetFileNameWithoutExtension(fileInfo.FullName);
                var relativeDirectory = fileInfo.Directory.FullName.Replace(AppDomain.CurrentDomain.BaseDirectory, string.Empty);
                var relativePath = string.Format("/{0}/{1}", relativeDirectory, name).Replace('\\', '/');
                sb.AppendFormat("\"{0}\": \"{1}\",\r\n", name, relativePath);
            });
            var code = sb.ToString().Trim().TrimEnd(',');
            code = TemplateResource.requireConfig.Replace("// {{PathPlaceHolder}}", code);
            File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Public/requireConfig.js"), code);
        }

        private static IEnumerable<FileInfo> GetJavascriptFileFullNames(string rootFullName)
        {
            var results = new List<FileInfo>();

            foreach (var directory in _directories)
            {
                var path = Path.Combine(rootFullName, directory.TrimStart('/'));
                if (!Directory.Exists(path)) continue;

                var files = Directory.GetFiles(path, "*.js", SearchOption.AllDirectories);
                results.AddRange(files.Select(t => new FileInfo(t)));
            }
            return results;
        }
    }
}